<template>
  <div class="log-view">
    <!-- 左侧日志文件列表 -->
    <div class="log-files-panel">
      <div class="header">
        <h2>日志文件</h2>
        <div class="actions">
          <el-button type="primary" size="small" @click="refreshLogFiles">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
      <el-table :data="logFiles" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="文件名">
          <template #default="{ row }">
            <el-button 
              link 
              type="primary" 
              @click="selectLogFile(row)"
              :class="{ 'is-active': currentFile?.name === row.name }"
            >
              <el-tooltip 
                :content="row.name" 
                placement="top" 
                :show-after="300"
              >
                <span class="truncate">{{ row.name }}</span>
              </el-tooltip>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="modified" label="修改时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.modified) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button-group>
              <el-button 
                type="primary" 
                size="small"
                @click="handleViewLog(row, false)"
              >
                查看
              </el-button>
              <el-button 
                type="success" 
                size="small"
                @click="handleViewLog(row, true)"
              >
                实时
              </el-button>
              <el-button 
                type="warning" 
                size="small"
                @click="handleAnalyzeLog(row, '24h')"
              >
                分析
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 右侧日志内容 -->
    <div class="log-content-panel">
      <div v-if="currentFile" class="log-content">
        <div class="header">
          <div class="title">
            <h3>{{ currentFile.name }}</h3>
            <el-tag size="small" :type="isRealtime ? 'success' : 'info'">
              {{ isRealtime ? '实时' : '静态' }}
            </el-tag>
          </div>
          <div class="actions">
            <el-button-group>
              <el-button 
                type="primary" 
                size="small"
                @click="toggleRealtime"
              >
                {{ isRealtime ? '停止' : '实时' }}
              </el-button>
              <el-button 
                type="success" 
                size="small"
                @click="handleCopyContent"
              >
                复制
              </el-button>
              <el-button 
                type="warning" 
                size="small"
                @click="handleDownload"
              >
                下载
              </el-button>
            </el-button-group>
          </div>
        </div>
        <div class="log-viewer" ref="logViewer">
          <div v-for="(line, index) in logLines" :key="index" class="log-line">
            {{ line }}
          </div>
        </div>
      </div>
      <div v-else class="no-file-selected">
        <el-empty description="请选择要查看的日志文件" />
      </div>
    </div>

    <!-- 日志分析对话框 -->
    <el-dialog
      v-model="analysisDialog.visible"
      :title="'日志分析 - ' + (currentFile?.name || '')"
      width="80%"
    >
      <div v-loading="analysisDialog.loading">
        <div class="analysis-header">
          <el-radio-group v-model="analysisDialog.period" @change="handleAnalyzeLog(currentFile!, analysisDialog.period)">
            <el-radio-button label="1h">最近1小时</el-radio-button>
            <el-radio-button label="24h">最近24小时</el-radio-button>
            <el-radio-button label="7d">最近7天</el-radio-button>
          </el-radio-group>
        </div>
        <div v-if="analysisDialog.data" class="analysis-content">
          <el-row :gutter="20">
            <!-- 基本统计信息 -->
            <el-col :span="8">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>基本统计</span>
                  </div>
                </template>
                <div class="stats-grid">
                  <div class="stat-item">
                    <div class="stat-label">总请求数</div>
                    <div class="stat-value">{{ analysisDialog.data.totalRequests }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-label">成功请求</div>
                    <div class="stat-value success">{{ analysisDialog.data.successRequests }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-label">失败请求</div>
                    <div class="stat-value error">{{ analysisDialog.data.errorRequests }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-label">平均响应大小</div>
                    <div class="stat-value">{{ formatFileSize(analysisDialog.data.avgResponseSize) }}</div>
                  </div>
                </div>
              </el-card>
            </el-col>

            <!-- 状态码分布 -->
            <el-col :span="8">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>状态码分布</span>
                  </div>
                </template>
                <el-table :data="formatStatusCodes(analysisDialog.data.statusCodes)" size="small">
                  <el-table-column prop="code" label="状态码" width="80">
                    <template #default="{ row }">
                      <el-tag :type="getStatusCodeType(row.code)">{{ row.code }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="count" label="次数" />
                  <el-table-column prop="percentage" label="占比">
                    <template #default="{ row }">
                      {{ ((row.count / analysisDialog.data.totalRequests) * 100).toFixed(2) }}%
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>

            <!-- 请求方法统计 -->
            <el-col :span="8">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>请求方法</span>
                  </div>
                </template>
                <el-table :data="formatTopItems(analysisDialog.data.topMethods)" size="small">
                  <el-table-column prop="item" label="方法" width="80">
                    <template #default="{ row }">
                      <el-tag>{{ row.item }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="count" label="次数" />
                  <el-table-column prop="percentage" label="占比">
                    <template #default="{ row }">
                      {{ ((row.count / analysisDialog.data.totalRequests) * 100).toFixed(2) }}%
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="mt-4">
            <!-- Top IP -->
            <el-col :span="8">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>Top IP</span>
                  </div>
                </template>
                <el-table :data="formatTopItems(analysisDialog.data.topIPs)" size="small">
                  <el-table-column prop="item" label="IP" show-overflow-tooltip />
                  <el-table-column prop="count" label="次数" width="80" />
                  <el-table-column prop="percentage" label="占比" width="80">
                    <template #default="{ row }">
                      {{ ((row.count / analysisDialog.data.totalRequests) * 100).toFixed(2) }}%
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>

            <!-- Top URL -->
            <el-col :span="8">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>Top URL</span>
                  </div>
                </template>
                <el-table :data="formatTopItems(analysisDialog.data.topURLs)" size="small">
                  <el-table-column prop="item" label="URL" show-overflow-tooltip />
                  <el-table-column prop="count" label="次数" width="80" />
                  <el-table-column prop="percentage" label="占比" width="80">
                    <template #default="{ row }">
                      {{ ((row.count / analysisDialog.data.totalRequests) * 100).toFixed(2) }}%
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>

            <!-- Top User Agent -->
            <el-col :span="8">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>Top User Agent</span>
                  </div>
                </template>
                <el-table :data="formatTopItems(analysisDialog.data.topUserAgents)" size="small">
                  <el-table-column prop="item" label="User Agent" show-overflow-tooltip />
                  <el-table-column prop="count" label="次数" width="80" />
                  <el-table-column prop="percentage" label="占比" width="80">
                    <template #default="{ row }">
                      {{ ((row.count / analysisDialog.data.totalRequests) * 100).toFixed(2) }}%
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Delete } from '@element-plus/icons-vue';
import { LogService, type LogFile, type LogAnalysis } from '@/services/log.service';
import { formatDate, formatFileSize } from '../utils/format';

// 状态
const loading = ref(false);
const logFiles = ref<LogFile[]>([]);
const currentFile = ref<LogFile | null>(null);
const logLines = ref<string[]>([]);
const isRealtime = ref(false);
const logViewer = ref<HTMLElement | null>(null);
let realtimeTimer: number | null = null;

// 日志分析对话框
const analysisDialog = ref({
  visible: false,
  loading: false,
  period: '24h' as '1h' | '24h' | '7d',
  data: null as LogAnalysis | null
});

// 获取日志文件列表
const refreshLogFiles = async () => {
  loading.value = true;
  try {
    logFiles.value = await LogService.getLogFiles();
  } catch (error) {
    ElMessage.error('获取日志文件列表失败');
  } finally {
    loading.value = false;
  }
};

// 选择日志文件
const selectLogFile = (file: LogFile) => {
  currentFile.value = file;
  handleViewLog(file, false);
};

// 查看日志内容
const handleViewLog = async (file: LogFile, realtime: boolean) => {
  currentFile.value = file;
  isRealtime.value = realtime;
  await refreshLogContent();

  if (realtime) {
    startRealtimeUpdate();
  }
};

// 刷新日志内容
const refreshLogContent = async () => {
  if (!currentFile.value) return;

  try {
    console.log('currentFile.value.path', currentFile.value.path);
    const content = await LogService.readLogFile(
      currentFile.value.path,
      1000,
      isRealtime.value
    );
    logLines.value = content.lines;
    
    // 滚动到底部
    if (isRealtime.value) {
      setTimeout(() => {
        if (logViewer.value) {
          logViewer.value.scrollTop = logViewer.value.scrollHeight;
        }
      }, 100);
    }
  } catch (error) {
    ElMessage.error('读取日志内容失败');
    console.error('Failed to read log content:', error);
  }
};

// 开始实时更新
const startRealtimeUpdate = () => {
  stopRealtimeUpdate();
  realtimeTimer = window.setInterval(refreshLogContent, 2000);
};

// 停止实时更新
const stopRealtimeUpdate = () => {
  if (realtimeTimer) {
    window.clearInterval(realtimeTimer);
    realtimeTimer = null;
  }
};

// 切换实时模式
const toggleRealtime = () => {
  isRealtime.value = !isRealtime.value;
  if (isRealtime.value) {
    startRealtimeUpdate();
  } else {
    stopRealtimeUpdate();
  }
};

// 分析日志
const handleAnalyzeLog = async (file: LogFile, period?: '1h' | '24h' | '7d') => {
  if(file) {
    currentFile.value = file;
  }
  analysisDialog.value.visible = true;
  analysisDialog.value.loading = true;
  try {
    const data = await LogService.analyzeLog(
      file.path,
      period || analysisDialog.value.period
    );
    analysisDialog.value.data = data;
  } catch (error) {
    ElMessage.error('分析日志失败');
    console.error('Failed to analyze log:', error);
  } finally {
    analysisDialog.value.loading = false;
  }
};

// 复制日志内容
const handleCopyContent = async () => {
  try {
    await navigator.clipboard.writeText(logLines.value.join('\n'));
    ElMessage.success('已复制到剪贴板');
  } catch (error) {
    ElMessage.error('复制失败');
    console.error('Failed to copy:', error);
  }
};

// 下载日志文件
const handleDownload = () => {
  if (!currentFile.value) return;

  const content = logLines.value.join('\n');
  const blob = new Blob([content], { type: 'text/plain' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = currentFile.value.name;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

// 格式化状态码数据
const formatStatusCodes = (codes: Record<string, number>) => {
  return Object.entries(codes).map(([code, count]) => ({
    code,
    count
  }));
};

// 格式化 Top 数据
const formatTopItems = (items: Record<string, number>) => {
  return Object.entries(items)
    .map(([item, count]) => ({ item, count }))
    .slice(0, 10);
};

// 获取状态码类型
const getStatusCodeType = (code: string) => {
  const num = parseInt(code);
  if (num < 200) return 'info';
  if (num < 300) return 'success';
  if (num < 400) return 'warning';
  return 'danger';
};

// 组件卸载时清理定时器
onUnmounted(() => {
  stopRealtimeUpdate();
});

// 初始化
refreshLogFiles();
</script>

<style scoped>
.log-view {
  height: 100%;
  display: flex;
  gap: 20px;
  padding: 20px;
  background: var(--el-bg-color-page);
}

.log-files-panel {
  flex: 2;
  flex-shrink: 0;
  background: var(--el-bg-color);
  border-radius: 8px;
  padding: 16px;
  display: flex;
  flex-direction: column;
}

.log-content-panel {
  flex: 3;
  min-width: 0;
  background: var(--el-bg-color);
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.actions {
  display: flex;
  gap: 8px;
}

.log-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.log-viewer {
  flex: 1;
  overflow-y: auto;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  padding: 16px;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
}

.log-line {
  margin: 0;
  padding: 2px 0;
}

.no-file-selected {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
}

.analysis-header {
  margin-bottom: 20px;
  text-align: center;
}

.analysis-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  color: var(--el-color-primary);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 12px;
  background: var(--el-fill-color-light);
  border-radius: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.stat-value.success {
  color: var(--el-color-success);
}

.stat-value.error {
  color: var(--el-color-danger);
}

.mt-4 {
  margin-top: 16px;
}

:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
}

.is-active {
  font-weight: bold;
}
</style> 